package com.javasea.spring.proxy.Aa;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

class BankCardAtomicReferenceTest {

    private static volatile AtomicReference<BankCard> bankCardRef = new AtomicReference(new BankCard("cxuan", 100));

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true) {
                    // 先读取全局的引用
                    final BankCard card = bankCardRef.get();
                    // 构造一个新的账户，存入一定数量的钱
                    BankCard newCard = new BankCard(card.getAccountName(), card.getMoney() + 100);
                    // 最后把新的账户的引用赋给原账户
//                  bankCard = newCard;
//                    bankCardRef.set(newCard);
                    // 使用 CAS 乐观锁进行非阻塞更新
                    if (bankCardRef.compareAndSet(card, newCard)) {
                        System.out.println(Thread.currentThread().getName() + ">>>" + newCard);
                        break;
                    }
                    try {
                        TimeUnit.MICROSECONDS.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
